document.addEventListener('DOMContentLoaded', () => {
  const form = document.getElementById('scriptForm');
  const generateBtn = document.getElementById('generateBtn');
  const loadingIndicator = document.getElementById('loadingIndicator');
  const scriptContent = document.getElementById('scriptContent');

  form.addEventListener('submit', async (e) => {
    e.preventDefault();

    // 获取表单数据
    const theme = document.getElementById('theme').value;
    const characters = document.getElementById('characters').value;
    const background = document.getElementById('background').value;

    // 显示加载指示器
    loadingIndicator.classList.remove('hidden');
    generateBtn.disabled = true;
    scriptContent.innerHTML = '';

    try {
      const response = await fetch('/api/generate', {
        method: 'POST',
        headers: {
          'Content-Type': 'application/json',
        },
        body: JSON.stringify({
          model: 'qwen2.5:7b',
          prompt: `主题：${theme}\n背景：${background}\n角色：${characters}`,
          stream: false
        }),
      });

      if (!response.ok) {
        throw new Error(`HTTP error! status: ${response.status}`);
      }

      const data = await response.json();
      scriptContent.textContent = data.response;
    } catch (error) {
      console.error('Error:', error);
      scriptContent.innerHTML = `<div class="error">生成失败，请重试。错误信息：${error.message}</div>`;
    } finally {
      loadingIndicator.classList.add('hidden');
      generateBtn.disabled = false;
    }
  });
});

// 修改 callOllamaAPI 函数
async function callOllamaAPI(prompt) {
    try {
        console.log('Sending request to API...');
        const response = await fetch('/api/generate', {  // 使用相对路径访问我们的代理服务器
            method: 'POST',
            headers: {
                'Content-Type': 'application/json',
            },
            body: JSON.stringify({
                model: "qwen2.5:7b",
                prompt: prompt,
                stream: false
            })
        });
        
        if (!response.ok) {
            throw new Error(`HTTP error! status: ${response.status}`);
        }
        
        const data = await response.json();
        console.log('Response data:', data);
        return data.response;
    } catch (error) {
        console.error('调用API时出错:', error);
        throw error;
    }
}

// 添加 appendMessage 函数
function appendMessage(type, content) {
    const chatContainer = document.getElementById('chat-container');
    const messageDiv = document.createElement('div');
    messageDiv.className = `chat-message ${type}-message`;
    messageDiv.textContent = content;
    chatContainer.appendChild(messageDiv);
    chatContainer.scrollTop = chatContainer.scrollHeight;
}

// 修改 handleUserInput 函数
async function handleUserInput() {
    const userInput = document.getElementById('user-input').value;
    if (!userInput.trim()) return;

    try {
        // 显示用户输入
        appendMessage('user', userInput);
        document.getElementById('user-input').value = '';

        // 显示加载状态
        const loadingDiv = document.createElement('div');
        loadingDiv.className = 'loading';
        loadingDiv.textContent = '思考中...';
        document.getElementById('chat-container').appendChild(loadingDiv);

        // 调用Ollama API
        const response = await callOllamaAPI(userInput);
        
        // 移除加载状态
        loadingDiv.remove();
        
        // 显示AI响应
        appendMessage('assistant', response);
    } catch (error) {
        console.error('Error:', error);
        appendMessage('assistant', '抱歉，生成剧本时出现错误，请稍后重试。');
    }
}


